package kr.lgh.sms_creditcard.Setting;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import kr.lgh.sms_creditcard.R;
import kr.lgh.sms_creditcard.BankType.BankInfo;
import kr.lgh.sms_creditcard.DB.SQLiteDBHelper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/*
 *  1. Card_Table 생성
 *  2. Msg.Table 생성
 *  3. Category_Table 생성
 */
public class SettingActivity extends ListActivity {
	boolean[] mSelect;
	SQLiteDBHelper dbHelper;
	ArrayList<String> cardList = new ArrayList<String>();
	BankInfo bankinfo;
	ProgressDialog progressBar;
	Handler mHadler;

	String row = ""; // 폰번호
	String msg = ""; // 메세지 본문
	String t_date = ""; // 지정된 형식의 날짜s
	long date; // 날짜
	public static int FINSH = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.setting, android.R.layout.simple_list_item_1);
		setListAdapter(adapter);

		dbHelper = new SQLiteDBHelper(this);
		cardList = dbHelper.select_CardList();
		mSelect = dbHelper.select_CheckState(cardList.size());

		for (int i = 0; i < mSelect.length; i++) {
			Log.d("TAG", "mSelect[" + i + "] : " + mSelect[i]);
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		switch (position) {

		// 사용자 카드 목록 설정
		case 0:
			String[] arCard = cardList.toArray(new String[cardList.size()]);
			for (int i = 0; i < arCard.length; i++) {
				arCard[i] = cardList.get(i);
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("카드를 선택하시오")
					.setMultiChoiceItems(arCard, mSelect,
							new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
									mSelect[which] = isChecked;
								}
							})
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									String[] userCard = getResources()
											.getStringArray(R.array.user_card);
									for (int i = 0; i < userCard.length; i++) {
										Log.d("TAG", "mSelect[" + i + "] :"
												+ mSelect[i]);
										dbHelper.setCheck_State(mSelect);
									}
								}
							}).setNegativeButton("취소", null).show();
			break;

		// 이전 문자 등록
		case 1:

			new DBThread().execute();
			List<BankInfo> bank_list = dbHelper.readAllData();

			for (BankInfo kb : bank_list) {
				String log = "id : " + kb.getS_id() + " / year : "
						+ kb.getS_year() + " / month : " + kb.getS_month()
						+ " / date : " + kb.getS_date() + " / time : "
						+ kb.getS_time() + " / money : " + kb.getS_money()
						+ " / place : " + kb.getS_place() + " / card : "
						+ kb.getS_card() + " / category : "
						+ kb.getS_category() + "/ card_table_id : "
						+ kb.getS_cardT_id() + " / category_table_id : "
						+ kb.getS_categoryT_id();
				Log.d("TAG", log);
			}

			break;
		// 카테고리 설정
		case 2:
			Intent intent = new Intent(this, CategoryList.class);
			startActivity(intent);
			break;
		}
	}

	public class DBThread extends AsyncTask<Void, Void, Void> {
		ProgressDialog progressDlg;

		@Override
		// Loading Dialog 생성
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(SettingActivity.this, "알림!",
					"SMS목록을 DB로 생성 중...");
		}

		@Override
		// Loading Dialog 제거
		protected void onPostExecute(Void result) {
			Log.d("TAG", "onPostExecute");
			progressDlg.dismiss();
		}

		@Override
		// DB를 생성.
		protected Void doInBackground(Void... params) {
			Log.d("TAG", "doInBackground");
			Uri allMessage = Uri.parse("content://sms/");
			Uri receiveMessage = Uri.parse("content : // sms/inbox");
			ContentResolver cr = getContentResolver();
			Cursor cur = cr.query(allMessage, null, null, null, null);
			Log.d("TAG", "테스트 진행중..");
			while (cur.moveToNext()) {
				row = cur.getString(cur.getColumnIndex("address")); // 발신자의
																	// 폰번호(연락처)
				msg = cur.getString(cur.getColumnIndex("body")); // 메시지 본문
				date = cur.getLong(cur.getColumnIndex("date")); // 날짜

				SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); // 년월일
																					// 형식으로
																					// 설정
				Calendar calendar = Calendar.getInstance(); // 날짜 인스턴스 생성
				calendar.setTimeInMillis(date); // 날짜를 지정한 형식으로 설정
				String formattedDate = formatter.format(calendar.getTime()); // 지정한
																				// 형식으로
																				// 문자열
																				// 생성
				ArrayList<String> arNumber = dbHelper.select_CardNumberList();

				if (arNumber.contains(row)) {

					// 대구BC
					if (arNumber.get(0).equals(row)) {
						int cardT_id = dbHelper.select_CardToID("대구BC");
						bankinfo = new BankInfo();
						bankinfo = (BankInfo) bankinfo.divide_DaeguBC(msg,
								formattedDate, "대구BC", cardT_id);
						dbHelper.insert_MsgData(bankinfo, formattedDate, "대구BC");
					}
					// DGB
					else if (arNumber.get(1).equals(row)) {
						int cardT_id = dbHelper.select_CardToID("DGB");
						bankinfo = new BankInfo();
						bankinfo = (BankInfo) bankinfo.divide_DGBbank(msg,
								formattedDate, "DGB", cardT_id);
						dbHelper.insert_MsgData(bankinfo, formattedDate, "DGB");
					}
					// KB국민체크
					else if (arNumber.get(2).equals(row)) {
						int cardT_id = dbHelper.select_CardToID("KB국민체크");
						bankinfo = new BankInfo();
						bankinfo = (BankInfo) bankinfo.divide_KBBank(msg,
								formattedDate, "KB국민체크", cardT_id);
						dbHelper.insert_MsgData(bankinfo, formattedDate,
								"KB국민체크");
					}
				}
			} // end of while()
			Log.d("TAG", "doItBackGround() 탈출");
			return null;
		} // end of doInBackground()
	}
}
